package com.jiming.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiming.common.utils.PageUtils;
import com.jiming.common.utils.Query;

import com.jiming.product.dao.PmsCategoryDao;
import com.jiming.product.entity.PmsCategoryEntity;
import com.jiming.product.service.PmsCategoryService;


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = this.page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<PmsCategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<PmsCategoryEntity> listWithTree() {
        //查处出所有分类
        List<PmsCategoryEntity> pmsCategoryEntities = baseMapper.selectList(null);
        //组装成父子树型结构
        List<PmsCategoryEntity> levelOne = pmsCategoryEntities.stream().filter(v -> v.getParentCid() == 0)
                .map((menu) -> {menu.setChildList(getChildList(menu,pmsCategoryEntities));
                    return menu;
                })
                .sorted((v1,v2) -> {
                    return (v1.getSort() == null ? 0 : v1.getSort()) - (v2.getSort() == null ? 0 : v2.getSort());
                })
                .collect(Collectors.toList());
        return levelOne;
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查找所有菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<PmsCategoryEntity> getChildList(PmsCategoryEntity root,List<PmsCategoryEntity> all){
        List<PmsCategoryEntity> childList = all.stream().filter(CategoryEntity -> {
            //找到子菜单
            return root.getCatId() == CategoryEntity.getParentCid();
        }).map(CategoryEntity -> {
            // 递归
            CategoryEntity.setChildList(getChildList(CategoryEntity,all));
            return CategoryEntity;
        }).sorted((v1,v2) -> {
            //排序
            return (v1.getSort() == null ? 0 : v1.getSort()) - (v2.getSort() == null ? 0 : v2.getSort());
        }).collect(Collectors.toList());
        return childList;
    }

}